import * as React from 'react';
import Collapse from 'antd/es/collapse/Collapse';
import { RouteComponentProps } from 'react-router';
import { inject, observer, Observer } from 'mobx-react';
import { FriendStore } from '../../store/FriendStore';
import { ChatStore } from '../../store/ChatStore';
import { SystemStore } from '../../store/SystemStore';
import { GroupStore } from '../../store/GroupStore';
import { NavLink } from 'react-router-dom';
import { FriendItem } from '../../interface/IFriend';
import { GroupItem } from '../../interface/IGroup';
import './Team.less';
import { AvatorWithPhoto } from '../../component/avatorWithPhoto/AvatorWithPhoto';
import { ChatGrOrFrType } from '../../interface/IChat';
import { detailType, MainStore } from '../../store/MainStore';
import { tr } from '../../i18n/tr';
import { RequestStore } from '../../store/RequestStore';
import { List as VList } from 'react-virtualized/dist/es/List';
import { AutoSizer } from 'react-virtualized/dist/es/AutoSizer';
import { CellMeasurer, CellMeasurerCache } from 'react-virtualized/dist/es/CellMeasurer';
import deviceManager from '../../net/DeviceManager';
import Badge from 'antd/es/badge';
import UserSearch from '../../component/UserSearch/UserSearch';
import { DeptStore } from '../../store';
import { DeptList, EmployItem, IChatEmployee, IDeptItem, IEmployee } from '../../interface/IDept';
const Panel = Collapse.Panel;

export interface ITeamProps extends RouteComponentProps {
	noRead: number;
}
interface WithStoreGroup extends ITeamProps {
	friendStore: FriendStore;
	chatStore: ChatStore;
	deptStore: DeptStore;
	mainStore: MainStore;
	systemStore:SystemStore;
	requestStore: RequestStore;
}
export interface ITeamState {
	openKeys: string[];
	fHeights: any[];
	// friends: FriendItem[],
	// groups: GroupItem[],
	gHeights: any[];
	activeKey: any[] // 新增状态
}
@inject('friendStore', 'chatStore', 'deptStore', 'mainStore', 'requestStore','systemStore')
@observer
class TeamView extends React.Component<ITeamProps, ITeamState> {
	constructor(props: ITeamProps) {
		super(props);
		this.state = {
			openKeys: ['friend'],
			fHeights: [],
			gHeights: [],
			// friends: [],
			// groups: [],
			activeKey: [] // 新增状态
		};
	}
	rootSubmenuKeys = ['request', 'group', 'friend'];
	get injected() {
		return this.props as WithStoreGroup;
	}

	onOpenChange = (openKeys: string[]) => {
		const latestOpenKey = openKeys.find((key) => this.state.openKeys.indexOf(key) === -1);
		if (latestOpenKey && this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
			this.setState({ openKeys });
		} else {
			this.setState({
				openKeys: latestOpenKey ? [latestOpenKey] : []
			});
		}
	};

	onClick = (id: string) => {
		const user = this.injected.systemStore.user;
		if( user.userId+'' == id){
			return;return	
		}

		this.injected.chatStore.changeSelectChat(id);
	};

	goFriendChat = (friend: EmployItem) => {
		const user = this.injected.systemStore.user;
		if( user.userId == friend.userId){
			console.error('这个是自己')
			return;
		}
		//this.injected.chatStore.changeCurrentChat(friend);
		this.injected.mainStore.showFriendInfo(detailType.messageGroup,friend);
	};

	goGroupChat = (group:IEmployee) => {
		this.injected.chatStore.changeCurrentChat(group);
	};

	showRequest = () => {
		this.injected.chatStore.goNewFriend();
		deviceManager.sendUpdateSelfInfoMsg();
		this.injected.requestStore.readRequest();
	};

	measureFriendCache = new CellMeasurerCache({
		fixedWidth: true,
		minHeight: 100
	});

	measureGroupCache = new CellMeasurerCache({
		fixedWidth: true,
		minHeight: 100
	});

	getFHeight = (data: { index: number }) => {
		const row = this.state.fHeights.find((item) => item.index == data.index);
		return row ? row.height : 100;
	};

	getGHeight = (data: { index: number }) => {
		const row = this.state.gHeights.find((item) => item.index == data.index);
		return row ? row.height : 100;
	};

	onCollapseChange = (activeKey: string[]) => {
    this.setState({ activeKey });
  };

	public render() {
		let groups:DeptList = this.injected.deptStore.deptList.concat()
		const filterText = this.injected.mainStore.filterTxt
		if( filterText ){
			groups = groups.map((item,index)=>{
				let employees = item.employees.filter(item => {
					let name = item.nickname;
					return name.indexOf(filterText) > -1

				})
				return {
					...item, employees
				}
			})
		}

		const renderItemGroup = ({ index, key, parent, style }: any, employees:IChatEmployee[]) => {
			const item = employees[index];
			return (
				<CellMeasurer
					cache={this.measureGroupCache}
					key={key}
					parent={parent}
					columnIndex={index}
					bordered={false}
				>
					{/* <Menu.Item key={groups[data.index].id}> */}

					<NavLink
						style={style}
						to={`${this.props.match.url}/${item.userId}`}
						onClick={() => this.goGroupChat(item)}
						activeClassName="selected"
						className="list-new-item"
					>
						<AvatorWithPhoto 
						size={40}
						type={ChatGrOrFrType.group} 
						id={item.userId+''} classN="userphoto"
						 />
						<span className="item-right friend-name">{item.nickname}</span>
					</NavLink>
					{/* </Menu.Item> */}
				</CellMeasurer>
			);
		};
		const renderFriends = (friends:IChatEmployee[])=>{
			return friends.map((item,index)=>{
				const isMe = item.userId == this.injected.systemStore.user.userId;
				return (
					<NavLink
						to={`${this.props.match.url}/${friends[index].userId}`}
						onClick={() => this.goFriendChat(friends[index])}
						activeClassName="selected"
						className={`list-new-item ${isMe?'list-new-item-disable':''}`}
					>
						<AvatorWithPhoto
							size={40}
							type={ChatGrOrFrType.group}
							id={friends[index].userId + ''}
							classN="head userphoto"
						/>
						<span className="item-right friend-name">
							{friends[index].nickname }{ isMe?'(我)':''}
						</span>
					</NavLink>
				);	
			})
		}

		

		const firstKey = [groups.length ? groups[0].companyId : '']
		return (
			<div className="chart-list chart-list-team">
				<UserSearch></UserSearch>
				<div className='chat-list-team-wrapper'>
					<Collapse defaultActiveKey={[]} activeKey={this.state.activeKey} onChange={this.onCollapseChange } accordion={false} bordered={false} >
					{
						groups.map((item, index)=>{
							return (
								<Panel header={`${item.departName}(${item.employees.length})`} key={index} id="contact-newfriend-list" forceRender={false}>
									{ renderFriends( item.employees  )}
								</Panel>
							)
						})
					}
					</Collapse>
					</div>
			</div>
		);
	}
}

// 使用 React.memo 包裹 TeamView 组件
const MemoizedTeamView = React.memo(TeamView);

export default MemoizedTeamView;
